package com.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.model.Article;
import com.model.Tag;
import com.model.User;
import com.search.SearchService;
import com.service.ArticleService;
import com.service.QuestionService;
import com.service.UserService;
import com.util.Page;
import com.util.RelationType;

@Controller
@RequestMapping("/c")
public class CHomeController {

	@Autowired
	private UserService userService;

	@Autowired
	private QuestionService questionService;

	@Autowired
	private ArticleService articleService;
	
	@Autowired
	private SearchService searchService;
	
	private final Log log = LogFactory.getLog(CHomeController.class);
	
	@RequestMapping(value = "/a/{id}", method = RequestMethod.GET)
	public ModelAndView detailA(HttpSession session, ModelAndView mav,
			@PathVariable("id") int articleId,
			@RequestParam(value = "page", required = false) Integer page) throws Exception {
		User user = (User) session.getAttribute("user");
		if (null == page) {
			page = 1;
		}
		Article article = articleService.findArticleByIdWithUser(articleId);
		if(article==null){
			throw new Exception();
		}
		List<Tag> taglist = articleService.findArticleTags(articleId);
		List commentlist = articleService.findCommentsByPage(articleId, page, 10);
		List relativelist = searchService.searchFromTag(taglist);
		mav.addObject("taglist", taglist);
		mav.addObject("article", article);
		mav.addObject("relativelist", relativelist);
		mav.addObject("commentlist", commentlist);
		mav.setViewName("detail_a");
		return mav;
	}

	@RequestMapping(value = "/q/{id}", method = RequestMethod.GET)
	public ModelAndView detailQ(HttpSession session, ModelAndView mav,
			@PathVariable("id") int questionId,
			@RequestParam(value = "page", required = false) Integer page) throws Exception {
		User user = (User) session.getAttribute("user");
		if (null == page) {
			page = 1;
		}
		Map question = questionService.findByIdWithUser(questionId);
		if(question==null){
			throw new Exception();
		}
		
		List<Tag> taglist = questionService.findQuestionTags(questionId);
		List commentlist = questionService.findCommentsByPage(questionId, page, 10);
		List relativelist = searchService.searchFromTag(taglist);
		mav.addObject("taglist", taglist);
		mav.addObject("question", question);
		mav.addObject("relativelist", relativelist);
		mav.addObject("commentlist", commentlist);
		mav.setViewName("detail_q");
		return mav;
	}

	@RequestMapping(value = "/home/{id}", method = RequestMethod.GET)
	public ModelAndView index(HttpSession session, ModelAndView mav, @PathVariable("id") int userId) {
		User user = (User) session.getAttribute("user");
		int relationType = RelationType.NO_MATTER;
		if (user != null) {
			relationType = userService.getUserRelation(user.getId(), userId);
		}
		User cuser = userService.getUserById(userId);
		if (cuser == null) {
			return new ModelAndView("exception");
		}
		List<Tag> taglist = userService.getUserTags(userId);

		Page qpage = questionService.getAnswerdQuestionByPage(userId, 1, 3, true);
		Page apage = articleService.findPageByUserIdPublic(userId, 1, 3);

		mav.addObject("relationType", relationType);
		mav.addObject("user", cuser);
		mav.addObject("tags", taglist);
		mav.addObject("questions", qpage);
		mav.addObject("articles", apage);

		mav.setViewName("c_home");
		return mav;
	}

	@RequestMapping(value = "/answer/{id}", method = RequestMethod.GET)
	public ModelAndView answer(HttpSession session, ModelAndView mav,
			@PathVariable("id") int userId,
			@RequestParam(value = "page", required = false) Integer page) {
		User user = (User) session.getAttribute("user");
		int relationType = RelationType.NO_MATTER;
		if (user != null) {
			relationType = userService.getUserRelation(user.getId(), userId);
		}
		if (null == page) {
			page = 1;
		}
		User cuser = userService.getUserById(userId);
		if (cuser == null) {
			return new ModelAndView("exception");
		}
		List<Tag> taglist = userService.getUserTags(userId);

		Page qpage = questionService.getAnswerdQuestionByPage(userId, page, 15, true);

		mav.addObject("relationType", relationType);
		mav.addObject("user", cuser);
		mav.addObject("tags", taglist);
		mav.addObject("questions", qpage);

		mav.setViewName("c_answerd");
		return mav;
	}

	@RequestMapping(value = "/self/{id}", method = RequestMethod.GET)
	public ModelAndView self(HttpSession session, ModelAndView mav, @PathVariable("id") int userId,
			@RequestParam(value = "page", required = false) Integer page) {
		User user = (User) session.getAttribute("user");
		int relationType = RelationType.NO_MATTER;
		if (user != null) {
			relationType = userService.getUserRelation(user.getId(), userId);
		}
		if (null == page) {
			page = 1;
		}
		User cuser = userService.getUserById(userId);
		if (cuser == null) {
			return new ModelAndView("exception");
		}
		List<Tag> taglist = userService.getUserTags(userId);

		Page apage = articleService.findPageByUserIdPublic(userId, page, 15);

		mav.addObject("relationType", relationType);
		mav.addObject("user", cuser);
		mav.addObject("tags", taglist);
		mav.addObject("articles", apage);

		mav.setViewName("c_self");
		return mav;
	}

	@RequestMapping(value = "/follow/{id}", method = RequestMethod.GET)
	public ModelAndView follow(HttpSession session, ModelAndView mav,
			@PathVariable("id") int userId,
			@RequestParam(value = "page", required = false) Integer page) {
		User user = (User) session.getAttribute("user");
		int relationType = RelationType.NO_MATTER;
		if (user != null) {
			relationType = userService.getUserRelation(user.getId(), userId);
		}
		if (null == page) {
			page = 1;
		}
		User cuser = userService.getUserById(userId);
		if (cuser == null) {
			return new ModelAndView("exception");
		}
		List<Tag> taglist = userService.getUserTags(userId);

		Page userPage = userService.findMyAttensionForPage(userId, page, 16);

		mav.addObject("relationType", relationType);
		mav.addObject("user", cuser);
		mav.addObject("tags", taglist);
		mav.addObject("follows", userPage);

		mav.setViewName("c_follow");
		return mav;
	}

	@RequestMapping(value = "/fans/{id}", method = RequestMethod.GET)
	public ModelAndView fans(HttpSession session, ModelAndView mav, @PathVariable("id") int userId,
			@RequestParam(value = "page", required = false) Integer page) {
		User user = (User) session.getAttribute("user");
		int relationType = RelationType.NO_MATTER;
		if (user != null) {
			relationType = userService.getUserRelation(user.getId(), userId);
		}
		if (null == page) {
			page = 1;
		}
		User cuser = userService.getUserById(userId);
		if (cuser == null) {
			return new ModelAndView("exception");
		}
		List<Tag> taglist = userService.getUserTags(userId);

		Page userPage = userService.findAttensiondMeForPage(userId, page, 16);

		mav.addObject("relationType", relationType);
		mav.addObject("user", cuser);
		mav.addObject("tags", taglist);
		mav.addObject("fans", userPage);

		mav.setViewName("c_fans");
		return mav;
	}

	@RequestMapping(value = "/ask-question", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> askQuestion(@RequestBody Map map, HttpSession session) {
		Map<String, Object> result = new HashMap<String, Object>();
		User user = (User) session.getAttribute("user");
		if (user == null) {
			result.put("ok", false);
			result.put("msg", "请先登录");
			return result;
		}
		int customerId = (Integer) map.get("customerId");
		boolean isAnonymous = (Boolean) map.get("isAnonymous");
		int isAnonymousInt = isAnonymous ? 1 : 0;
		String question = (String) map.get("question");
		questionService.addQuestion(customerId, user.getId(), question, 1, 1, isAnonymousInt);

		result.put("ok", true);
		result.put("msg", "");
		return result;
	}

	@RequestMapping(value = "/read-comment/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> readComment(HttpSession session, @PathVariable("id") int id,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam("type") String type) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (type.equals("article")) {
			List commentlist = articleService.findCommentsByPage(id, page, 10);
			result.put("ok", true);
			result.put("data", commentlist);
		}
		else if (type.equals("question")) {
			List commentlist = questionService.findCommentsByPage(id, page, 10);
			result.put("ok", true);
			result.put("data", commentlist);
		}
		else {
			result.put("ok", false);
			result.put("msg", "");
			return result;
		}
		return result;

	}

	@RequestMapping(value = "/add-comment/{id}", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addComment(HttpSession session, @RequestBody Map map, @PathVariable("id") int id) {
		Map<String, Object> result = new HashMap<String, Object>();
		String type = (String) map.get("type");
		User user = (User) session.getAttribute("user");
		if (user == null) {
			result.put("ok", false);
			result.put("msg", "请先登录");
			return result;
		}
		String content = (String) map.get("content");
		if (type.equals("article")) {
			articleService.addComment(id, user.getId(), content);
			result.put("ok", true);
			result.put("msg", "");
		}
		else if (type.equals("question")) {
			questionService.addComment(id, user.getId(), content);
			result.put("ok", true);
			result.put("msg", "");
		}
		else {
			result.put("ok", false);
			result.put("msg", "");
			return result;
		}
		return result;
	}
	
	
	@RequestMapping(value = "/add-tag/{id}", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addArticleTag(@RequestBody Map map, @PathVariable("id") int id) {
		Map<String, Object> result = new HashMap<String, Object>();
		String tagName = (String) map.get("tagname");
		log.debug(">>>>>>>>>>>>>>>>>>tagName:"+tagName);
		String type = (String) map.get("type");

		if (type.equals("article")) {
			articleService.addArticleTag(id, tagName);
			result.put("ok", true);
			result.put("msg", "");
		}
		else if (type.equals("question")) {
			questionService.addQuestionTag(id, tagName);
			result.put("ok", true);
			result.put("msg", "");
		}
		else {
			result.put("ok", false);
			result.put("msg", "");
			return result;
		}
		return result;
	}
}
